package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrOctetString;
import org.road0329.dlt698.asn1.axdr.AxdrType;

import java.io.IOException;

public class SID extends AxdrType {
    private byte[] dataCode = null;
    private Unsigned32 indi = null;
    private AxdrOctetString fdata = null;

    public SID() {
    }

    public byte[] getDataCode() {
        return dataCode;
    }

    public Unsigned32 getIndi() {
        return indi;
    }

    public AxdrOctetString getFdata() {
        return fdata;
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    public void setAll(Unsigned32 indi, AxdrOctetString fdata) {
        this.indi = indi;
        this.fdata = fdata;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.indi = new Unsigned32();
        this.indi.setConst();
        codeLength += this.indi.decode(input);
        this.fdata = new AxdrOctetString();
        codeLength += this.fdata.decode(input);
        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength;
        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (int i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if (this.indi != null && this.fdata != null) {
                codeLength = 0;
                codeLength += this.fdata.encode(output);
                codeLength += this.indi.encode(output);
            } else {
                throw new RuntimeException("fdata || indi is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.toByteArray();
    }

    @Override
    public String toString() {
        if (this.indi != null && this.fdata != null) {
            return "sequence: {" + "indi: " + this.indi + ", fdata: " + this.fdata + "}";
        } else {
            return "indi || fdata is null";
        }
    }
}



